import { useGlobalStore, usePermissionStore, useUserStore } from "@/stores";
import type { AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { Authorization, Bearer, LOGIN_URL } from "./systemConfig";

/**
 * @description 请求拦截器
 * @param config 请求配置
 * @returns InternalAxiosRequestConfig
 */
export function requestInterceptors(config: InternalAxiosRequestConfig): InternalAxiosRequestConfig {
  const useUser = useUserStore();
  if (config.headers && typeof config.headers.set === "function") {
    config.headers.set(Authorization, Bearer + useUser.token);
  }
  return config;
}

/**
 * @description 响应拦截器
 * @param response 响应配置
 * @returns ResultData
 */
export function responseInterceptors(response: AxiosResponse): AxiosResponse {
  const { data } = response;
  switch (data.code) {
    case 200:
      return data;
    case 401:
      useUserStore().clearCacheHandler();
      usePermissionStore().clearCacheHandler();
      useGlobalStore().clearGlobalConfig();
      sessionStorage.clear();
      location.href = LOGIN_URL;
      break;
    case 403:
      location.href = "/403";
      break;
    case 500:
      location.href = "/500";
      break;
    default:
      break;
  }
  return data;
}
